package visualization.singleview;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import math.Quality;
import dataTypes.ISequenceData;

public class CutPanel extends JPanel implements ChangeListener {
	private static final long serialVersionUID = 6361074250767692944L;

	private static final int NUMBEROFWINDOWSIZES = 15;

	// TODO: Update all references to window size, number and such.

	ISequenceData seqData;
	double[][] qualityAvg;
	int seqLength;
	int threshold = 30;
	JSpinner thresholdSpinner;

	public CutPanel(ISequenceData seqData) {
		this.seqData = seqData;

		qualityAvg = Quality.calcWindowQuality(seqData, 1, 1, 50);

		thresholdSpinner = new JSpinner(new SpinnerNumberModel(30, 0, 100, 1));
		thresholdSpinner.addChangeListener(this);
		this.add(thresholdSpinner);

		this.seqLength = seqData.getSeqLength();
	}

	public void paintComponent(Graphics g) {
		int heightOffset = Math.round((float) (this.getHeight() * 0.1));
		int widthOffset = Math.round((float) (this.getWidth() * 0.1));

		double baseLength = (this.getWidth() * 0.8) / seqLength;
		double heightBetween = (this.getHeight() * 0.8) / NUMBEROFWINDOWSIZES;

		for (int pos = 0; pos < seqLength; pos++) {
			for (int seq = 0; seq < NUMBEROFWINDOWSIZES; seq++) {
				if (qualityAvg[seq][pos] < threshold) {
					g.setColor(Color.BLACK);
				} else {
					g.setColor(Color.RED);
				}
				g.fillRect((int) Math.floor(widthOffset + pos * baseLength),
						(int) (heightOffset + seq * heightBetween), (int) Math
								.ceil(baseLength), (int) Math.ceil(Math.min(
								Math.max(heightBetween - 2, 1), baseLength)));
			}
		}
	}

	public void stateChanged(ChangeEvent arg0) {
		SpinnerModel numberModel = thresholdSpinner.getModel();
		if (numberModel instanceof SpinnerNumberModel) {
			threshold = ((SpinnerNumberModel) numberModel).getNumber()
					.intValue();
		}
	}
}
